package cn.glenn._04weibo.controller;

import cn.glenn._04weibo.base.response.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/upload/")
public class UploadController {
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) {
        String filename = file.getOriginalFilename();//获取文件名
        String suffix = filename.substring(filename.lastIndexOf("."));//获取后缀名
        filename = UUID.randomUUID() + suffix;//生成唯一名
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd/");//定义时间路径格式
        String datePath = dateFormat.format(new Date());//创建时间路径

        String dir = "d:/files";
        File dirFile = new File(dir+datePath);//创建对应目录
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String filePath = dir+datePath+filename;//服务器存储路径
        try {
            file.transferTo(new File(filePath));//上传文件
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败");
        }
        return JsonResult.success(datePath+filename);//返回文件访问路径
    }
}
